<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class C_cart extends CI_Controller {
	function __construct(){
		parent::__construct();
	}

	/**
	 * Index Page for this controller.
	 */
	public function index(){
		$data['produk'] = $this->incart_produk();
		$this->load->view('main/v_cart', $data);
	}
	
	function incart_produk(){
		$i=0;
		$id = '';
		if(sizeof($this->session->userdata('cart')) > 0 && $this->session->userdata('cart') !== false){
			foreach($this->session->userdata('cart') as $row_cart){
				$id .= $row_cart['productid'] . ',';
				$i++;
			}
		}
		$result = $this->m_public_function->incart_produk(substr($id,0,-1));
		$result_session = $this->session->userdata('cart');
		if($result !== ''){
			foreach($result as $row){
				foreach($result_session as $row_session){
					$produk_db = $row->produk_id;
					$produk_ses = $row_session['productid'];
					if($produk_db == $produk_ses){
						$row->qty = $row_session['qty'];
					}
				}
			}
		}
		return $result;
	}
	function checkout(){
		$subtotal = trim(@$_POST['subtotal']);
		$list_produkid = trim(@$_POST['list_produkid']);
		$user_id = $this->session->userdata('DX_user_id');
		$now = date('Y-m-d H:i');
		if($user_id !== '' && $user_id !== false){
			$saldo = $this->m_public_function->get_saldouser($user_id);
			if($saldo >= $subtotal){
				$saldo_now = $saldo - $subtotal;
				$reset_saldo = $this->m_public_function->reset_saldouser($user_id,$saldo_now);
				if($reset_saldo == 1){
					foreach($this->session->userdata('cart') as $row_cart){
						$this->m_public_function->insert_history($row_cart['productid'] , $user_id, $now);
					}
					$this->session->unset_userdata('cart');
				}
				echo $reset_saldo;
			}else{
				echo 2;
			}
		}else{
			echo 3;
		}
	}
	function remove_product(){
		$pid = trim(@$_POST['pid']);
		$pid = intval($pid);
		$max=count($this->session->userdata['cart']);
		for($i=0;$i<$max;$i++){
			if($pid==$this->session->userdata['cart'][$i]['productid']){
				$cartlist = $this->session->userdata('cart');
				unset($cartlist[$i]);
				$this->session->set_userdata('cart',$cartlist);
			}
		}
		$max2 = count($this->session->userdata['cart']);
		if($max > $max2){
			echo 1;
		}else{
			echo 0;
		}
	}
	function update_product(){
		$pid = trim(@$_POST['pid']);
		$jumlahbeli = trim(@$_POST['jumlahbeli']);
		$pid = intval($pid);
		$max=count($this->session->userdata['cart']);
		for($i=0;$i<$max;$i++){
			if($pid==$this->session->userdata['cart'][$i]['productid']){
				$cartlist = $this->session->userdata('cart');
				$cartlist[$i]['qty'] = $jumlahbeli;
				$this->session->set_userdata('cart',$cartlist);
			}
		}
		$max2 = count($this->session->userdata['cart']);
		echo 1;
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */